<template>
  <div class="reg-person">
    <base-header></base-header>
    <div class="nng-register">
      <div :style="{ 'padding-left': 10 + 'px' }">
        <span>
            <router-link to="/login" class="login">登录</router-link> 
        </span>
        <span> / </span>
        <span class="register-text">注册</span>
      </div>
      <div class="form-box">
        <el-form ref="ruleForm" :rules="rules" :model="ruleForm">
          <el-form-item class="region" required>
            <el-form-item class="region-left">
                
                <el-select v-model="region" placeholder="+86" clearable filterable>
                    <el-option v-for="item in phoneAreaList" :key="item.id" :label="'+'+item.areanum" :value="item.areanum"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="phone" class="region-right">
                <el-input v-model="ruleForm.phone" placeholder="请输入手机号码"></el-input>
            </el-form-item>
          </el-form-item>
          <el-form-item prop="code">
              <el-input v-model="ruleForm.code" placeholder="请输入短信验证码"></el-input>
              <el-button class="send-code" :disabled="isDisabled" @click="sendCode">发送验证码</el-button>
          </el-form-item>
          <el-form-item prop="password">
              <el-input type="password" v-model="ruleForm.password" placeholder="请输入登录密码" show-password></el-input>
          </el-form-item>
          <el-form-item prop="checkpwd">
              <el-input type="password" v-model="ruleForm.checkpwd" placeholder="请确认登录密码" show-password></el-input>
          </el-form-item>
          <el-form-item class="nng-regist">
              <el-button :style="{ 'background': '#4065E0', 'color': '#ffffff', 'width': 108 + 'px','margin-right': 140+ 'px' }" @click="submitForm('ruleForm')">确定</el-button>
              <el-link :underline="false" :style="{ 'color': '#36C2CF' }" @click="joinBusiness('ruleForm')">加入企业 ➡️</el-link>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <router-view></router-view>
    <base-picture></base-picture>
    <base-footer></base-footer>
    
  </div>
</template>

<script>
import { register, sendCodeRequest, areaList } from 'api/index'
import BaseHeader from '@/components/base/header/Header'
import BaseFooter from '@/components/base/footer/Footer'
import BasePicture from '@/components/base/picture/Picture'
import { mapMutations } from 'vuex'
export default {
  name: 'PerRegister',
  data () {
    //自定义手机号验证
    const checkPhone = (rule, value, callback) => {
      if (value == "") {
        return callback(new Error("手机号不能为空"));
      } else {
        const reg = /^[0-9]*$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    }
    // 验证验证码
    const checkCode = (rule, value, callback) => {
        if(value == "") {
            return callback(new Error("请输入验证码"));
        }else{
            const reg1 = /^[0-9]{6}$/
            if (!reg1.test(value)){
                return callback(new Error("验证码必须为6位数"))
            }else{
                callback();
            }
        }
    }
    // 验证密码
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入平台登录密码"));
      } else {
        // var reg1 = /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[a-zA-Z0-9]{8}$/;
        var reg1 = /^(?=.*?[0-9])(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[~!@#$%^&*])[0-9A-Za-z~!@#$%^&*)]{8,}$/;
        if (reg1.test(value)) {
          callback();
        }else {
          return callback(new Error("密码由8位数大小写字母、数字和特殊字符组成"));
        }
      }
    };
    // 确认密码
    var definePwd = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.password) {
            callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
    };
      return {
          isDisabled: false,
          region: '',   // 手机号前缀
          ruleForm: {
            phone: '',
            code: '',
            password: '',
            checkpwd: ''
          },
          rules: {
            // region: [
            //     { required: true, message: '请输入区域', trigger: 'change' }
            // ],
            phone: [
                { validator: checkPhone, required: true, trigger: 'change' }
            ],
            code: [
                { validator: checkCode, required: true, trigger: 'change'}
            ],
            password: [
                { validator: validatePass, required: true, trigger: 'change' }
            ],
            checkpwd: [
                { validator: definePwd, required: true, trigger: 'change' }
            ]
          },
          phoneAreaList: []
      }
  },
  components: {
      BaseHeader,
      BaseFooter,
      BasePicture
  },
  methods: {
    ...mapMutations([
      'saveNngUserId'
    ]),
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var params = {
              phone: this.ruleForm.phone,
              pwd: this.ruleForm.password,
              rpwd: this.ruleForm.checkpwd,
              code: this.ruleForm.code,
              userType: 1,
              appId: 'nng0031'
            }
            // 个人注册  存 nng_uid
            register(params).then(res => {
              console.log(res)
              if(res.response_code == 0){
                
                  this.$message.success("注册成功")
                  this.$router.push({ name: 'Login' })
                
              }else{
                this.$message.error(res.reason)
              }
            })
            // this.userPhone(this.ruleForm.phone)  存用户账号
            // this.$router.push({ name: 'Login' })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      joinBusiness(formName){ // 选择加入企业
        this.$refs[formName].validate(valid => {
          if(valid) {
            var params = {
              phone: this.ruleForm.phone,
              pwd: this.ruleForm.password,
              rpwd: this.ruleForm.checkpwd,
              code: this.ruleForm.code,
              userType: 1,
              appId: 'nng0031'
            }
            // userType为2表示商家
            register(params).then(res => {
              console.log(res)
              if(res.result.nng_uid){
                //if(res.result.nng_uid){
                  // 保存 nng_uid
                  // window.localStorage.setItem('nngUserId',res.result.nng_uid)
                  this.saveNngUserId(res.result.nng_uid)
                //}
                
                this.$router.push({ name: 'SelectRole' })
              }else{
                this.$message.warning(res.reason)
              }
            })
            
          }else{
            return false;
          }
        })
      },
      sendCode(){
        var params = {
          info: this.ruleForm.phone,
          method: 'phone',
          areaCode: this.region.toString() || '86'
        }
        sendCodeRequest(params).then(res => {
          console.log(res)
          if(res.response_code == 0){
            this.isDisabled = true
            setTimeout(() => {
              this.isDisabled = false
            }, 10000);
          }
        })
      },
      // 获取区号列表
    getAreaList(){
      areaList().then(res => {
        console.log(res)
        res.result.area_code.unshift({ areanum: 86, cname: '中国大陆', ename: 'China', fee: 1 })
        this.phoneAreaList = res.result.area_code
      })
    }
  },
  created(){
    this.getAreaList()
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/varible';
.reg-person{
  height: 100%;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: #ffffff;
  z-index: 20;
  .nng-register{
    position: absolute;
    left: 83px;
    top: 50%;
    transform: translateY(-50%);
    .login{
      color: #bbbbbb;
      font-size: 15px;
    }
    .register-text{
      color: #666666;
      font-size: 15px;
    }
    .form-box{
      padding-top: 55px;
      padding-left: 10px;
      padding-right: 10px;
      box-sizing: border-box;
    .send-code{
        margin-left: 10px;
        background-color: #36C2CF;
        color: #ffffff;
    }
  }
}
}
</style>
